package models;

import com.alibaba.fastjson.JSONArray;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * Created by yangxianming on 2021/3/31.
 */
public class CheckPower {
    public static ReturnJson checkPower(HttpServletRequest request, String businessClassName, String nextClassName){
        ReturnJson returnJson = new ReturnJson();
        HttpSession sh = request.getSession();
        String sessionId = "";

        Cookie[] cookies = request.getCookies();
        if (Objects.equals(cookies, null)){
            returnJson.setResult(0, null, "非法请求");
            return returnJson;
        }else {
            boolean isJSESSIONID = true;
            for (Cookie cookie: cookies){
                if (Objects.equals(cookie.getName(), "JSESSIONID")){
                    isJSESSIONID = false;
                    sessionId = cookie.getValue();
                    if (Objects.equals(sh.getAttribute(sessionId), null)){
                        //通过存在session中Attribute中的key判断有没有登陆
                        returnJson.setResult(0, null, "没有权限1");
                        return returnJson;
                    }
                }
            }
            //如果没有JSESSIONID就提示没权限
            if (isJSESSIONID){
                returnJson.setResult(0, null, "没有权限2");
                return returnJson;
            }
        }
        //获得用户权限
        User user = (User)sh.getAttribute(sessionId);
        JSONArray power = user.getPower();

        //验证权限
        if (!power.contains(businessClassName)){
            returnJson.setResult(0, null, "没有此功能权限:" + businessClassName);
            return returnJson;
        }
        if (!power.contains(nextClassName)){
            returnJson.setResult(0, null, "没有此功能权限:" + businessClassName + "." + nextClassName);
            return returnJson;
        }

        return returnJson;
    }
}
